import axios from "axios";
import store from "../store";
import qs from "qs"


//设置默认的请求链接头
var instance = axios.create({
	baseURL: 'http://127.0.0.1:9000' //设置默认的链接请求头
})

let a = 0
instance.interceptors.request.use(
	config => {
		let token = window.localStorage.getItem("token");
		if (token != null || token != undefined) {
			a += 1;
			if(a == 1)console.log("请求得到token=" + token);
			//将登录后的token设置为请求的token值
			config.headers.Authorization = "Bearer " + token;
		}
		return config;
	}
)

instance.interceptors.response.use(
	response => {
		console.log("获取得到成功的响应:")
		console.dir(response.data.data)
		console.log("------------------------")
		return response
	},
	error => {
		console.log("出现异常报错,状态码为：" + error.response.status)
		if (error.response) {
			switch (error.response.status) {
				case 401:
					store.state.msg = "当前用户未登录或密码错误";
					localStorage.setItem("token", "");
					router.push('/login') //跳转返回到登录
					break;
				case 403:
					store.state.msg = "当前用户禁止访问，没有权限";
					break;
				case 500:
					store.state.msg = "输入数据异常";
					break;
				default:
					console.log("有问题，未开发该注解....")
					store.state.msg = "当前系统在开发中";
			}
		}
		return Promise.reject(error.response.status)//返回接口的错误信息
	}
)

//get 键值对
export let $get = (url, obj) => {
	return instance.get(url, {
		params: obj
	})
}
//键值对格式
export let $postx = (url, obj) => {
	const o = qs.stringify(obj)
	return instance.post(
		url, o, {
			header: {
				'Content-Type': 'application/x-www-form-urlencoded;charset=utf8'
			}
		}
	)
}
//此处的obj为formData
export let $postf = (url, obj) => {
	return instance.post(
		url,
		obj, {
			headers: {
				'Content-Type': 'multipart/form-data'
			}
		}
	)
}

//此处的obj为JSON对象，可以直接传参
export let $postj = (url, josn) => {
	return instance.post(url, josn, {
		header: {
			'Content-Type': 'application/json;charset=utf8'
		}
	})
}